<?php
namespace Common\Util;

class LLPay 
{
	//支付URL
	private $payUrl = 'https://yintong.com.cn/llpayh5/payment.htm';
	
	/**
	 * 支付
	 * @author 刘新
	 */
	public function pay($data, $signType)
	{
		$param = $this->payParam($data);
		$res = \Common\Util\Util::curl($param, array('method' => 3), $this->payUrl);
	}
	
	
	/**
	 * 异步通知
	 * @param array $data
	 */
	public function notifyVerify($param)
	{
		$return = array('error' => 1, '支付失败');
		
		//支付成功
		if(strtoupper($param['result_pay']) === 'SUCCESS') {
			if($param['oid_partner'] !== C('llpay.partner')) {
				$return['info'] = '商户编号错误';
			} else if(!$param['sign'] || !$param['sign_type']) {
				$return['info'] = '缺少签名参数';
			} else if(!$param['oid_paybill']) {
				$return['info'] = '连连支付订单号';
			} else {
				$sign = $this->sign($param);
				if($sign !== $param['sign']) {
					$return['info'] = '签名错误';
				} else {
					$return = array('error' => 0, '支付成功');
				}
			}
		}
		
		return $return;
	}
	
	/**
	 * 构造请求参数
	 * @param array $data
	 */
	private function payParam($data)
	{
		$param = array (
				'oid_partner' => C('llpay.partner'),
				'version' => C('llpay.version'),
				'user_id' => $data['user_id'],
				
				//1-Android 2-ios 3-WAP
				'app_request' => $data['app_request'],
				
				'sign_type' => C('llpay.signType'),
				'busi_partner' => '101001',
				'no_order' => $data['order_no'],
				'dt_order' => $data['order_date'],
				'name_goods' => $data['fund_name'],
				'money_order' => $data['amount'],
				'notify_url' => C('llpay.notifyUrl'),
				'url_return' => C('llpay.returnUrl'),
				
				//订单有效期
				//'valid_order' => $data['valid_order'],
				//证件类型，默认为0,即身份证
				'id_type' => 0,
				'card_no' => $data['card_no'],
				'acct_name' => $data['acc_name'],
				'id_no' => $data['social_no'],
				'no_agree' => $data['no_agree'],
		);

		/*风险控制参数*/
		//商品类型
		$risk_item['frms_ware_category'] = '2004';
		//商户用户唯一标识
		$risk_item['user_info_mercht_userno'] = $data['user_id'];
		//商户用户注册时间
		$risk_item['user_info_dt_register'] = $data['user_register'];
		//商户用户姓名
		$risk_item['user_info_full_name'] = $data['user_realname'];
		//商户用户证件类型
		$risk_item['user_info_id_type'] = 0;
		//商户用户证件号码
		$risk_item['user_info_id_no'] = '';
		$param['risk_item'] = $risk_item;
		
		$param['sign'] = $this->sign($param);
		return $param;
	}
	
	/**
	 * 签名
	 * @param array $param
	 */
	public function sign($data) 
	{
		ksort($data);
		$signType = strtolower(C('llpay.signType'));

		//md5签名
		if($signType === 'md5') {
			foreach($data as $key => $val) {
				if(isset($val) && $key !== 'sign') {
					$str .= $key . '=' . $val . '&';
				}
			}
			
			$str .= 'key=' . C('llpay.key');
			return hash('md5', $str);
		}
	}
}